<script setup lang="ts">
import { getSubmissionStatsApi } from '@/api/problem/stats';
import { ref, computed, onMounted, watch, reactive } from 'vue';
import { useUserStore } from '@/stores/user';
import { getUserLanguageSubmitApi, getRecentlySubmittedListApi } from '@/api/problem/submit';
import { getRecentlyPublishedSolutionListApi } from '@/api/problem/solution';
import { useRouter } from 'vue-router';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh-cn'; // 导入中文语言包
import { Message, Modal } from '@arco-design/web-vue';
// Attempting a more general import if specific path fails for TS resolution
import { uploadImage } from '@/api/oss/oss';
import { updateUserInfoApi } from '@/api/auth/auth';

// Alias for consistency if needed, or use UploadRequestOption directly
type RequestOption = any; // Fallback type for now to avoid blocking lint errors
// UploadUserFile is often used for the file item in Arco
type FileItem = any; // Fallback type for now

dayjs.extend(relativeTime);
dayjs.locale('zh-cn'); // 设置 dayjs 使用中文

const userStore = useUserStore();
const languageData = ref<API.Problem.UserLanguageSubmitVo[]>([]);
const recentlySubmittedList = ref<API.Problem.RecentPassVo[]>([]);
const router = useRouter();

const selectedYear = ref(0); // 0 for "Past year", otherwise specific year

const currentYear = new Date().getFullYear();
const yearOptions = computed(() => {
  const options = [{ label: '过去一年', value: 0 }];
  for (let i = 1; i <= 3; i++) {
    const year = currentYear - i;
    options.push({ label: String(year), value: year });
  }
  return options;
});

// Raw data from server/generation, a flat list of days with counts FOR THE EFFECTIVE PERIOD
const submissionCalendarData = ref<API.DailySubmissionStat[]>([]); // 使用 API 类型
const isLoadingCalendar = ref(false); // 添加加载状态
const maxConsecutiveDays = ref(0); // 新增 ref 存储连续提交天数

// --- Edit Profile Modal ---
const isEditModalVisible = ref(false);
const editFormRef = ref(); // For form validation
const editForm = reactive<Pick<API.UserUpdateMyRequest, 'userName' | 'userProfile'>>({
  userName: '',
  userProfile: '',
});

const rules = {
  userName: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  userProfile: [{ maxLength: 200, message: '个人简介最多200字符', trigger: 'blur' }],
};

const openEditModal = () => {
  if (userStore.userInfo) {
    editForm.userName = userStore.userInfo.userName || '';
    editForm.userProfile = userStore.userInfo.userProfile || '';
  }
  isEditModalVisible.value = true;
};

const handleUpdateProfile = async () => {
  const validation = await editFormRef.value?.validate();
  if (validation) {
    Message.error('请检查输入');
    return;
  }

  if (!userStore.userInfo) {
    Message.error('用户信息丢失，无法更新');
    return;
  }

  const params: API.UserUpdateMyRequest = {
    userName: editForm.userName,
    userProfile: editForm.userProfile,
    userAvatar: userStore.userInfo.userAvatar, // Keep current avatar
  };

  try {
    const res = await updateUserInfoApi(params);
    if (res.code === 0 && res.data) {
      // Update store
      userStore.userInfo = {
        ...userStore.userInfo,
        userName: params.userName,
        userProfile: params.userProfile,
      };
      Message.success('个人资料更新成功！');
      isEditModalVisible.value = false;
    } else {
      Message.error(res.message || '更新失败');
    }
  } catch (error: any) {
    Message.error(error.message || '更新个人资料时发生错误');
  }
};

// --- Helper Functions ---
function getDaysInMonth(year: number, month: number): number {
    return new Date(year, month + 1, 0).getDate(); // month is 0-indexed
}

const getSubmissionColor = (count: number) => {
  if (count === 0) return '#ebedf0';
  if (count < 3) return 'var(--color-primary-light-2)';
  if (count < 6) return 'var(--color-primary-light-3)';
  if (count < 9) return 'var(--color-primary-light-4)';
  return 'rgb(var(--primary-6))';
};

const isFutureDate = (dateString: string) => {
  if (dateString.startsWith('placeholder-')) return false;
  const date = new Date(dateString); date.setHours(0,0,0,0);
  const today = new Date(); today.setHours(0,0,0,0);
  return date > today;
};

interface DayInMonthBlock {
  date: string; 
  displayCount: number;
  isFuture: boolean;
  isPlaceholderInBlock: boolean; 
}

const getTooltipContent = (day: DayInMonthBlock) => {
  if (day.isPlaceholderInBlock) return null; 
  if (day.isFuture) return '未来日期';
  return `${day.date}: ${day.displayCount} 次提交`;
};

// 累计提交天数
const getActiveDays = computed(() => {
  // 直接基于 API 返回的原始数据计算
  return submissionCalendarData.value.filter(day => (day.count ?? 0) > 0).length;
});
// 总提交数
const getTotalSubmissions = computed(() => {
  return submissionCalendarData.value.reduce((acc, day) => acc + (day.count ?? 0), 0);
});

const monthlyGroupedCalendarData = computed(() => {
  const monthBlocks: { monthName: string; year: number; weeks: DayInMonthBlock[][] }[] = [];
  // 使用 API 返回的 submitDate 作为 key
  const dateDataMap = new Map(
    submissionCalendarData.value.map(d => [d.submitDate, d.count ?? 0]) // 使用 submitDate 并提供默认值 0
  );

  let iterMonthStartDate: Date, iterMonthEndDateBoundary: Date;
  const today = new Date(); today.setHours(0,0,0,0);

  // Define the overall period for month iteration
  if (selectedYear.value === 0) { // "Past year"
    iterMonthStartDate = new Date(today);
    iterMonthStartDate.setFullYear(today.getFullYear() - 1);
    iterMonthStartDate.setDate(1); // Start iterating from 1st of the month one year ago

    iterMonthEndDateBoundary = new Date(today);
    iterMonthEndDateBoundary.setDate(1); // Start with 1st of current month
    iterMonthEndDateBoundary.setMonth(today.getMonth() + 1); // Go to 1st of next month (exclusive end for month loop)

  } else { // Specific year
    iterMonthStartDate = new Date(selectedYear.value, 0, 1); // Jan 1st of selected year
    iterMonthEndDateBoundary = new Date(selectedYear.value + 1, 0, 1); // Jan 1st of NEXT year
  }
  
  for (let dLoopMonth = new Date(iterMonthStartDate); dLoopMonth < iterMonthEndDateBoundary; dLoopMonth.setMonth(dLoopMonth.getMonth() + 1)) {
    const currentYearVal = dLoopMonth.getFullYear();
    const currentMonthIdx = dLoopMonth.getMonth(); 
    const monthName = (currentMonthIdx + 1) + '月';

    const firstDayOfMonthDateObj = new Date(currentYearVal, currentMonthIdx, 1);
    const dayOfWeekForFirst = firstDayOfMonthDateObj.getDay(); 
    const numDaysInThisMonth = getDaysInMonth(currentYearVal, currentMonthIdx);

    const allCellsForMonth: DayInMonthBlock[] = [];
    const totalWeeksForMonth = Math.ceil((dayOfWeekForFirst + numDaysInThisMonth) / 7);
    const totalCellsToRender = totalWeeksForMonth * 7;

    for (let cellIdx = 0; cellIdx < totalCellsToRender; cellIdx++) {
      const dayOfMonth = cellIdx - dayOfWeekForFirst + 1;
      if (cellIdx < dayOfWeekForFirst || dayOfMonth > numDaysInThisMonth) {
        allCellsForMonth.push({
          date: `placeholder-${currentYearVal}-${currentMonthIdx}-cell${cellIdx}`,
          displayCount: 0,
          isFuture: false,
          isPlaceholderInBlock: true,
        });
      } else {
        const dateStr = `${currentYearVal}-${String(currentMonthIdx + 1).padStart(2, '0')}-${String(dayOfMonth).padStart(2, '0')}`;
        // 从 Map 中获取 count
        const count = dateDataMap.get(dateStr) || 0;
        
        let isEffectiveDay = true;
        const actualDate = new Date(dateStr); // Date of the current cell

        if (selectedYear.value === 0) { // "Past Year" strict period check
            let strictPeriodStart = new Date(today);
            strictPeriodStart.setFullYear(today.getFullYear() - 1); // One year ago today 00:00
            
            let strictPeriodEndExclusive = new Date(today);
            strictPeriodEndExclusive.setDate(today.getDate() + 1); // Tomorrow 00:00

            if (actualDate < strictPeriodStart || actualDate >= strictPeriodEndExclusive) {
                isEffectiveDay = false;
            }
        } 
        // For specific year, all days of that year are inherently effective if generated by dateStr

        allCellsForMonth.push({
          date: dateStr,
          displayCount: isEffectiveDay ? count : 0,
          isFuture: isEffectiveDay ? isFutureDate(dateStr) : false,
          isPlaceholderInBlock: !isEffectiveDay, 
        });
      }
    }

    const weeksForBlock: DayInMonthBlock[][] = [];
    for (let i = 0; i < allCellsForMonth.length; i += 7) {
      weeksForBlock.push(allCellsForMonth.slice(i, i + 7));
    }
    
    // Filter out months that are entirely placeholders AND not strictly part of the core 12/13 month display for "past year"
    if (selectedYear.value === 0) {
        const hasAnyNonPlaceholderDay = weeksForBlock.flat().some(day => !day.isPlaceholderInBlock);
        if (!hasAnyNonPlaceholderDay) {
            // This additional check can be refined if empty months are desired for past year continuity.
            // For now, if a month block (after strict period check) ends up as all placeholders, skip it.
            continue;
        }
    }

    monthBlocks.push({ monthName, year: currentYearVal, weeks: weeksForBlock });
  }
  return monthBlocks;
});

/**
 * 计算最大连续提交天数
 * @param data - API 返回的提交数据数组 (已确保仅包含 count > 0 的项)
 */
function calculateMaxConsecutiveDays(data: API.DailySubmissionStat[]) {
  if (!data || data.length === 0) {
    return 0;
  }

  // 1. 提取有提交的日期字符串并排序
  const submissionDates = data
    .map(d => d.submitDate) // 提取日期
    .filter((date): date is string => !!date) // 过滤掉 undefined 或 null 的日期
    .sort(); // YYYY-MM-DD 格式可以直接按字符串排序

  if (submissionDates.length === 0) {
    return 0;
  }
  if (submissionDates.length === 1) {
    return 1;
  }

  let currentStreak = 1;
  let maxStreak = 1;

  // 将日期字符串转为毫秒时间戳，方便计算差值
  const dateTimestamps = submissionDates.map(dateStr => new Date(dateStr).getTime());

  const oneDayInMs = 24 * 60 * 60 * 1000;

  for (let i = 1; i < dateTimestamps.length; i++) {
    const diff = dateTimestamps[i] - dateTimestamps[i - 1];

    // 检查日期是否连续 (允许一定的误差，例如夏令时，但通常 1 天就是精确的 oneDayInMs)
    // 为了简单起见，我们假设日期间隔严格等于 oneDayInMs
    if (diff === oneDayInMs) {
      currentStreak++;
    } else {
      // 如果日期不连续，重置当前 streak
      currentStreak = 1;
    }
    // 更新最大 streak
    maxStreak = Math.max(maxStreak, currentStreak);
  }

  return maxStreak;
}

const updateCalendarData = async () => {
  isLoadingCalendar.value = true;
  submissionCalendarData.value = []; // 清空旧数据
  maxConsecutiveDays.value = 0; // 重置连续天数
  try {
    const params: API.SubmissionStatsParams = {};
    if (selectedYear.value === 0) {
      params.period = 'pastYear';
    } else {
      params.period = String(selectedYear.value);
    }

    // 调用 API
    const res = await getSubmissionStatsApi(params);

    if (res.code === 0 && res.data) { // 假设 0 是成功状态码
      submissionCalendarData.value = res.data;
      // 在数据加载后计算连续提交天数
      // 确保只传递 count > 0 的数据给计算函数
      const activeDaysData = res.data.filter(day => (day.count ?? 0) > 0);
      maxConsecutiveDays.value = calculateMaxConsecutiveDays(activeDaysData);
    } else {
      console.error('Failed to fetch submission stats:', res.message);
      // Message.error(res.message || '加载提交数据失败'); // 如果需要错误提示
    }
  } catch (error) {
    console.error('Error fetching submission stats:', error);
    // Message.error('加载提交数据时发生网络错误'); // 如果需要错误提示
  } finally {
    isLoadingCalendar.value = false;
  }
};

const getUserLanguageSubmit = async () => {
  const res = await getUserLanguageSubmitApi();
  if (res.code === 0 && res.data) {
    languageData.value = res.data;
  }
}

const fetchRecentlySubmitted = async () => {
  try {
    const res = await getRecentlySubmittedListApi();
    if (res.code === 0 && res.data) {
      recentlySubmittedList.value = res.data;
    } else {
      console.error('Failed to fetch recently submitted list:', res.message);
    }
  } catch (error) {
    console.error('Error fetching recently submitted list:', error);
  }
};

const formatRelativeTime = (dateTimeString?: string) => {
  if (!dateTimeString) return '';
  return dayjs(dateTimeString).fromNow();
};

const goToSubmissionDetail = (submissionId?: string) => {
  if (submissionId) {
    const routeData = router.resolve(`/submission-detail/${submissionId}`);
    window.open(routeData.href, '_blank');
  }
};

onMounted(() => {
  updateCalendarData(); 
  getUserLanguageSubmit();
  fetchRecentlySubmitted();
});

watch(selectedYear, () => {
  updateCalendarData(); 
});

const customUploadRequest = async (options: RequestOption) => {
  const { fileItem, onSuccess, onError, onProgress } = options;
  // fileItem is now of type FileItem (aliased UploadUserFile), which should have a .file property
  const file = fileItem.file; 

  if (!file) {
    Message.error('未选择文件');
    onError(new Error('未选择文件')); 
    return { abort: () => {} };
  }

  const formData = new FormData();
  formData.append('file', file);
  
  // Pass fileItem to onProgress. It should be compatible with UploadUserFile.
  if (onProgress) onProgress(0.1, fileItem); 

  try {
    if (onProgress) onProgress(0.3, fileItem);
    const uploadRes = await uploadImage(formData); 
    if (onProgress) onProgress(0.7, fileItem);

    if (uploadRes.code === 0 && typeof uploadRes.data === 'string') {
      const newAvatarUrl = uploadRes.data;

      if (userStore.userInfo) {
        const currentUserInfoState = { ...userStore.userInfo }; 

        const updateParams: API.UserUpdateMyRequest = {
          userName: currentUserInfoState.userName,
          userProfile: currentUserInfoState.userProfile,
          userAvatar: newAvatarUrl,
        } as API.UserUpdateMyRequest;

        userStore.userInfo = { ...currentUserInfoState, userAvatar: newAvatarUrl };

        try {
          const backendUpdateRes = await updateUserInfoApi(updateParams);

          if (backendUpdateRes.code === 0 && backendUpdateRes.data === true) {
            Message.success('头像更新成功！');
            onSuccess(newAvatarUrl); 
          } else {
            Message.error(backendUpdateRes.message || '更新用户信息失败');
            userStore.userInfo = currentUserInfoState; 
            onError(new Error(backendUpdateRes.message || '更新用户信息失败'));
          }
        } catch (updateError: any) {
          Message.error(updateError.message || '更新用户信息接口调用失败');
          userStore.userInfo = currentUserInfoState; 
          onError(updateError); 
        }
      } else {
        Message.error('用户信息未加载，无法更新头像');
        onError(new Error('用户信息未加载'));
      }
    } else {
      Message.error(uploadRes.message || '图片上传失败');
      onError(new Error(uploadRes.message || '图片上传失败'));
    }
    if (onProgress) onProgress(1, fileItem); 
  } catch (error: any) {
    Message.error(error.message || '图片上传或用户更新处理失败');
    onError(error); 
    if (onProgress) onProgress(1, fileItem); 
  }

  return {
    abort: () => {
      console.log('Upload aborted.');
    },
  };
};

// --- Recently Passed & Solutions Tabs ---
const activeTabKey = ref('1'); // Default to the first tab: "最近通过"
const recentlyPublishedSolutions = ref<API.Problem.RecentlySolutionVo[]>([]);
const solutionsLoaded = ref(false);
const isLoadingSolutions = ref(false);

const fetchRecentlyPublishedSolutions = async () => {
  if (isLoadingSolutions.value) return;
  isLoadingSolutions.value = true;
  try {
    const res = await getRecentlyPublishedSolutionListApi();
    if (res.code === 0 && res.data) {
      recentlyPublishedSolutions.value = res.data;
      solutionsLoaded.value = true;
    } else {
      Message.error(res.message || '加载题解列表失败');
      solutionsLoaded.value = false; // Allow retry by resetting loaded state on error
    }
  } catch (error: any) {
    Message.error(error.message || '加载题解列表时发生网络错误');
    solutionsLoaded.value = false; // Allow retry
  } finally {
    isLoadingSolutions.value = false;
  }
};

const handleTabChange = (key: string | number) => {
  const tabKey = String(key);
  activeTabKey.value = tabKey;
  if (tabKey === '2' && !solutionsLoaded.value && !isLoadingSolutions.value) {
    fetchRecentlyPublishedSolutions();
  }
};

const handleSolutionItemClick = (solution: API.Problem.RecentlySolutionVo) => {
  if (solution.id) {
    const routeData = router.resolve({ name: 'solutionDetail', params: { solutionId: solution.id } });
    window.open(routeData.href, '_blank');
  } else {
    Message.error('无效的题解ID');
  }
};

</script>

<template>
  <div class="user-info-page">
    <a-layout>
      <a-layout-header class="header">
        <div style="display: flex">
          <a-upload
            :show-file-list="false"
            :custom-request="customUploadRequest"
            accept="image/*"
            class="avatar-uploader-trigger" 
          >
            <template #upload-button>
              <div class="avatar-container" style="position: relative; display: inline-block; cursor: pointer;">
                <a-avatar :size="64" shape="square" :image-url="userStore.userInfo?.userAvatar"></a-avatar>
                <div class="avatar-overlay">
                  <icon-edit /> 修改头像
                </div>
              </div>
            </template>
          </a-upload>
          <div class="account">
            <a-typography-text style="font-size: 20px; font-weight: 600"> {{ userStore.userInfo?.userName }} </a-typography-text>
            <a-typography-text type="secondary"> {{ userStore.userInfo?.userAccount }} </a-typography-text>
          </div>
        </div>
      </a-layout-header>
      <a-layout>
        <a-layout-sider class="sider">
          <a-button class="edit-info" status="danger" @click="openEditModal">编辑个人资料</a-button>
          <a-divider />
          <div class="profile">
            <a-typography-title :heading="6"> 个人简介 </a-typography-title>
            <a-typography-paragraph type="secondary" :ellipsis="{ rows: 2 }">
              {{ userStore.userInfo?.userProfile }}
            </a-typography-paragraph>
          </div>
          <a-divider />
          <a-descriptions size="small" title="语言" :column="1" :align="{ value: 'right' }">
            <a-descriptions-item v-for="item of languageData" :label="item.language">
              <p style="margin: 0%">
                通过数：<a-tag>{{ item.submitCount }}</a-tag>
              </p>
            </a-descriptions-item>
          </a-descriptions>
        </a-layout-sider>
        <a-layout-content>
          <a-row :gutter="20" :style="{ marginBottom: '20px' }">
            <a-col :span="12">
              <div :bordered="false" class="submit-pass-count">
                <div class="chars">图表统计区</div>
                <div class="pass-count">
                  <div class="info">
                    <p style="color: #1cbaba">简单</p>
                    <p>200/1230</p>
                  </div>
                  <div class="info">
                    <p style="color: #ffb700">中等</p>
                    <p>200/1230</p>
                  </div>
                  <div class="info">
                    <p style="color: #f63737">困难</p>
                    <p>200/1230</p>
                  </div>
                </div>
              </div>
            </a-col>
            <a-col :span="12">
              <a-card title="待开发" :bordered="false" :style="{ width: '100%' }">
                功能待定
              </a-card>
            </a-col>
          </a-row>
          <a-row :gutter="20" :style="{ marginBottom: '20px' }">
            <a-col :span="24">
              <a-card class="hot-day" :bordered="false" :style="{ width: '100%' }">
                <template #title>
                  <a-typography-text type="secondary" style="font-size: 14px">
                    {{ selectedYear === 0 ? '过去一年' : selectedYear + '年' }}共提交
                    <span style="color: #000; font-size: 18px">{{ getTotalSubmissions }}</span>次
                  </a-typography-text>
                </template>
                <template #extra>
                  <div class="hot-day-info">
                    <p style="margin-right: 15px">
                      累计提交天数:<span style="color: #262626; padding: 0 5px">{{ getActiveDays }}</span>
                      连续提交:<span style="color: #262626; padding-left: 5px">{{ maxConsecutiveDays }}</span>
                    </p>
                    <a-select
                      v-model="selectedYear"
                      :style="{ width: '100px' }"
                      :trigger-props="{ autoFitPopupMinWidth: true }"
                    >
                      <a-option v-for="option in yearOptions" :key="option.value" :value="option.value">{{ option.label }}</a-option>
                    </a-select>
                  </div>
                </template>
                
                <a-spin :loading="isLoadingCalendar" tip="加载日历中..." style="width: 100%;">
                  <div class="calendar-scroll-container">
                    <div class="calendar-months-outer-flex-container">
                      <div
                        v-for="(monthBlock, mbIndex) in monthlyGroupedCalendarData"
                        :key="`mb-${monthBlock.year}-${monthBlock.monthName}`"
                        class="month-block"
                      >
                        <div class="month-grid-squares">
                          <div
                            v-for="(week, weekIndex) in monthBlock.weeks"
                            :key="`week-${mbIndex}-${weekIndex}`"
                            class="calendar-week"
                          >
                            <a-tooltip
                              v-for="(day) in week"
                              :key="day.date"
                              :content="getTooltipContent(day)"
                              mini
                              position="top"
                              :disabled="day.isPlaceholderInBlock || day.isFuture"
                            >
                              <div
                                class="calendar-day"
                                :class="{
                                  'calendar-day-future': day.isFuture,
                                  'placeholder-day-in-block': day.isPlaceholderInBlock
                                }"
                                :style="{ backgroundColor: getSubmissionColor(day.displayCount) }"
                              ></div>
                            </a-tooltip>
                          </div>
                        </div>
                        <div class="month-label-for-block">{{ monthBlock.monthName }}</div>
                      </div>
                    </div>
                  </div>
                </a-spin>

                <div class="calendar-legend">
                  <span class="legend-label">少</span>
                  <div class="legend-boxes">
                    <div class="legend-box" style="background-color: #ebedf0"></div>
                    <div class="legend-box" style="background-color: var(--color-primary-light-2)"></div>
                    <div class="legend-box" style="background-color: var(--color-primary-light-3)"></div>
                    <div class="legend-box" style="background-color: var(--color-primary-light-4)"></div>
                    <div class="legend-box" style="background-color: rgb(var(--primary-6))"></div>
                  </div>
                  <span class="legend-label">多</span>
                </div>
              </a-card>
            </a-col>
          </a-row>
          <a-row :gutter="20">
            <a-col :span="24">
              <a-card>
                <a-tabs v-model:active-key="activeTabKey" @change="handleTabChange">
                  <a-tab-pane key="1" :title="'最近通过'">
                    <template #title> <icon-calendar /> 最近通过 </template>
                    <a-list class="zebra-list"> <template #header />
                      <a-list-item 
                        v-for="(item, index) in recentlySubmittedList" 
                        :key="item.submissionId" 
                        @click="goToSubmissionDetail(String(item.submissionId))"
                        style="cursor: pointer;"
                        :class="{ 'striped-item': index % 2 !== 0 }"
                      >
                        <a-list-item-meta :title="item.title">
                        </a-list-item-meta>
                        <template #extra>
                          <a-typography-text
                            type="secondary"
                            style="font-size: 12px"
                            >{{ formatRelativeTime(item.passTime) }}</a-typography-text
                          >
                        </template>
                      </a-list-item>
                    </a-list>
                  </a-tab-pane>
                  <a-tab-pane key="2" :title="'题解'">
                    <template #title> <icon-clock-circle /> 题解 </template>
                    <div v-if="activeTabKey === '2'"> 
                      <a-spin :loading="isLoadingSolutions" style="width: 100%; min-height: 100px;">
                        <a-list v-if="solutionsLoaded && recentlyPublishedSolutions.length > 0" class="zebra-list">
                          <a-list-item
                            v-for="solution in recentlyPublishedSolutions"
                            :key="solution.id" 
                            @click="handleSolutionItemClick(solution)" 
                            style="cursor: pointer;" 
                          >
                            <a-list-item-meta :title="solution.title || '暂无标题'">
                            </a-list-item-meta>
                            <template #extra>
                              <a-space size="large">
                                <a-typography-text type="secondary">
                                  <icon-eye /> {{ solution.views !== undefined ? solution.views : 'N/A' }} 浏览
                                </a-typography-text>
                              </a-space>
                            </template>
                          </a-list-item>
                        </a-list>
                        <a-empty v-else-if="solutionsLoaded && recentlyPublishedSolutions.length === 0" description="暂无最新题解" />
                        <a-result v-else-if="!isLoadingSolutions && !solutionsLoaded" status="error" title="加载失败">
                          <template #subtitle>请检查网络连接或稍后重试。</template>
                          <template #extra>
                            <a-button type="primary" @click="fetchRecentlyPublishedSolutions">重试</a-button>
                          </template>
                        </a-result>
                      </a-spin>
                    </div>
                  </a-tab-pane>
                </a-tabs>
              </a-card>
            </a-col>
          </a-row>
        </a-layout-content>
      </a-layout>
    </a-layout>

    <!-- Edit Profile Modal -->
    <a-modal
      v-model:visible="isEditModalVisible"
      title="编辑个人资料"
      @ok="handleUpdateProfile"
      @cancel="isEditModalVisible = false"
      :mask-closable="false"
      unmount-on-close
    >
      <a-form :model="editForm" :rules="rules" ref="editFormRef" layout="vertical">
        <a-form-item field="userName" label="用户名" validate-trigger="blur">
          <a-input v-model="editForm.userName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item field="userProfile" label="个人简介" validate-trigger="blur">
          <a-textarea
            v-model="editForm.userProfile"
            placeholder="请输入个人简介 (最多200字)"
            :max-length="{ length: 200, errorOnly: true }"
            show-word-limit
            allow-clear
            :auto-size="{ minRows: 3, maxRows: 6 }" 
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<style scoped>
p {
  margin: 0;
}
.user-info-page {
  max-width: 1200px;
  margin: 0 auto;
  margin-top: 10px;
}
.header {
  height: 96px;
  padding: 8px 0;
  margin-bottom: 24px;
}
.header .account {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  padding-left: 15px;
  padding-top: 8px;
}
.sider {
  width: 250px !important;
  padding: 18px 14px;
  background-color: white;
  margin-right: 25px;
  border-radius: 8px;
}
.edit-info {
  width: 100%;
}

:deep(.sider .arco-descriptions-size-small .arco-descriptions-item-value-block) {
  padding-right: 0 !important;
}

.submit-pass-count {
  width: 100%;
  background-color: #fff;
  height: 180px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-radius: 8px;
}
.submit-pass-count .chars {
  width: 280px;
  text-align: center;
}
.submit-pass-count .pass-count {
  height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
}
.submit-pass-count .info {
  width: 90px;
  text-align: center;
  font-size: 12px;
  font-weight: 600;
  background-color: #00000005;
  padding: 4px 0;
}
.submit-pass-count .info p:first-child {
  margin-bottom: 5px;
}
:deep(.hot-day .arco-select-view-single.arco-select-view-size-medium .arco-select-view-value) {
  font-size: 12px !important;
}
.hot-day-info {
  display: flex;
  align-items: center;
  color: #b7b9b9;
  font-size: 12px;
}

/* New Calendar Styles for LeetCode Look */
.calendar-scroll-container {
  overflow-x: auto; 
  padding-top: 16px;
  padding-bottom: 10px; 
}

.calendar-months-outer-flex-container {
  display: flex;
  flex-direction: row;
  gap: 12px; 
  width: 100%;
  justify-content: space-evenly; 
}

.month-block {
  display: flex;
  flex-direction: column;
  align-items: center; 
}

.month-grid-squares {
  display: flex; 
  flex-direction: row;
}

.calendar-week { 
  display: flex;
  flex-direction: column; 
  margin-right: 2.5px; 
}
.calendar-week:last-child {
  margin-right: 0;
}

.calendar-day {
  width: 8.86px;
  height: 8.86px;
  border-radius: 2px;
  margin: 1.5px 0; 
  background-color: #ebedf0; 
  cursor: pointer;
}

.calendar-day-future {
  opacity: 0.5;
}

.placeholder-day-in-block {
  background-color: transparent !important;
  pointer-events: none; 
  cursor: default;
}

.month-label-for-block {
  font-size: 10px;
  color: var(--color-text-3);
  margin-top: 5px;
  text-align: center;
}

.calendar-legend {
  display: flex;
  align-items: center;
  justify-content: flex-end; 
  margin-top: 10px;
  gap: 4px;
  padding-right: 5px;
}

.legend-label {
  font-size: 10px;
  color: var(--color-text-3);
}

.legend-boxes {
  display: flex;
  gap: 2px;
}

.legend-box {
  width: 10px; 
  height: 10px;
  border-radius: 2px;
}

:deep(.arco-spin) {
  min-height: 150px; /* 根据日历实际高度调整，防止加载时塌陷 */
  display: block;
}

/* 新增斑马纹样式 */
:deep(.zebra-list .arco-list-item.striped-item) {
  background-color: #f7f8fa; /* 你可以根据需要调整这个颜色 */
}

:deep(.zebra-list .arco-list-item) {
  padding-top: 10px; /* 调整列表项的上下内边距 */
  padding-bottom: 10px;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent black */
  color: white;
  display: flex;
  flex-direction: column; /* Stack icon and text vertically */
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  border-radius: inherit; /* If avatar has rounded corners, overlay should too */
  font-size: 12px; /* Adjust as needed */
  border-radius: 2px;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay icon-edit {
  margin-bottom: 4px; /* Space between icon and text */
}
</style>
